package com.xiaolei.openokjoke.Activitys

import android.animation.ValueAnimator
import android.content.Intent
import android.os.Bundle
import com.xiaolei.openokjoke.Base.BaseActivity
import com.xiaolei.openokjoke.Exts.*
import com.xiaolei.openokjoke.Net.APPNet
import com.xiaolei.openokjoke.Net.BaseRetrofit
import com.xiaolei.openokjoke.R
import kotlinx.android.synthetic.main.activity_qq_lucky.*
import android.graphics.Bitmap
import android.net.Uri
import android.os.Environment
import android.view.View
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.media.UMImage
import com.xiaolei.openokjoke.UM.UMShare
import java.io.File
import kotlin.concurrent.thread
import com.umeng.analytics.MobclickAgent


/**
 * QQ吉凶测验
 * Created by xiaolei on 2018/3/14.
 */
class QQLuckyActivity : BaseActivity()
{
    private val share by lazy {
        UMShare(this)
    }

    private val appNet by lazy {
        BaseRetrofit.create(APPNet::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?)
    {
        setContentView(R.layout.activity_qq_lucky)
        super.onCreate(savedInstanceState)
    }

    override fun initObj()
    {

    }

    override fun initView()
    {
        app_title.setRightTextVisible(View.GONE)
    }

    private fun useMyFont()
    {
        // 这里使用自定义字体
        grade.useMyFont()
        analysis.useMyFont()
        qq.useMyFont()
        qq_label.useMyFont()
        score.useMyFont()
        score_label.useMyFont()
        desc_title.useMyFont()
        desc.useMyFont()
    }

    override fun initData()
    {

    }

    override fun setListener()
    {
        app_title.setOnRightTextClick {
            app_title.setRightTextVisible(View.GONE)
            result_panel.collapse {
                control_panel.expand{
                    qq_et.text.clear()
                }
            }
        }
        app_title.setOnLeftImageClick { finish() }
        submit_btn.setOnClickListener {
            val qqNum = qq_et.text.toString().trim()
            if (qqNum.length < 6)
            {
                Toast("请输入正确的QQ号码")
            } else
            {
                val call = appNet.qqLucky(qqNum)
                submit_btn.isClickable = false
                call.enqueue(this, { result ->
                    if (result.isOk())
                    {
                        result.appdata?.let {

                            app_title.setRightTextVisible(View.VISIBLE)
                            useMyFont()
                            control_panel.hideKeyboard()

                            control_panel.collapse {
                                result_panel.show()
                                val animator = ValueAnimator.ofFloat(0f, 1f)
                                animator.addUpdateListener { it ->
                                    val alpha = it.animatedValue as Float
                                    result_panel.alpha = alpha
                                }
                                animator.duration = 1500
                                animator.start()

                                qq.text = it.qq
                                score.text = it.score
                                desc.text = "\u3000\u3000${it.desc}"
                                analysis.text = it.analysis
                                grade.text = it.grade
                            }
                        }
                    }
                }, {
                    submit_btn.isClickable = true
                    MobclickAgent.onEvent(this, "QQLuck_Click")
                }, {})
            }
        }

        click_2_share.setOnClickListener {
            click_2_share.gone()
            save2disk()
        }
    }

    /**
     * 保存到本地
     */
    private fun save2disk()
    {
        result_panel.isDrawingCacheEnabled = true
        result_panel.buildDrawingCache()
        val cacheBitmap = result_panel.drawingCache
        thread {
            val bitmap = Bitmap.createBitmap(cacheBitmap)
            val dcimDir = File(Environment.getExternalStorageDirectory(), "DCIM")
            val saveDir = File(dcimDir, "OKJoke")
            val saveFile = File(saveDir, "${System.currentTimeMillis()}.png")
            if (!saveDir.exists())
            {
                saveDir.mkdirs()
            }
            if (!saveFile.exists())
            {
                saveFile.createNewFile()
            }
            val fos = saveFile.outputStream()
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
            fos.flush()
            fos.close()
            runOnUiThread {
                sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(saveFile)))
                Toast("已保存至本地")
                click_2_share.show()
                share.shareImage(UMImage(this, saveFile)).open()
            }
        }
    }

    override fun loadData()
    {

    }

    override fun onResume()
    {
        MobclickAgent.onPageStart("QQLucky") //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写。"SplashScreen"为页面名称，可自定义)
        super.onResume()
    }

    override fun onPause()
    {
        MobclickAgent.onPageEnd("QQLucky") // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息。"SplashScreen"为页面名称，可自定义
        super.onPause()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
    {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
    }
}